//
//  EDLuckCashViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/26.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDLuckCashViewController.h"
#import "EDRichTextLabel.h"
#import "TwoBtnsView.h"

#define Start_X          30.0f      // 第一个按钮的X坐标
#define Start_Y          15.0f     // 第一个按钮的Y坐标
#define Width_Space      30.0f      // 2个按钮之间的横间距
#define Height_Space     15.0f     // 竖间距
#define Button_Height   35.0f    // 高
#define Button_Width    75.0f    // 宽

@interface EDLuckCashViewController ()
@property(nonatomic,strong)   UILabel * topLab;
@property(nonatomic,strong)UIScrollView * bgSc;
@property(nonatomic,strong)   NSDictionary * gameInfoDicc;
@property(nonatomic,strong)   UIView * btnsView;
@end

@implementation EDLuckCashViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gameInfoDicc = [NSDictionary dictionary];
    [self creatUI];
//    WEAKSELF
//    self.bgSc.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        //调用刷新方法
//        STRONGSELFFor(weakSelf);
//
//    }];
//    [self.bgSc.mj_header beginRefreshing];
    
      [self getLuckInfo];
    
}

-(void)creatUI{
    self.bgSc = [[UIScrollView alloc]init];
    self.bgSc.frame = CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, kScreenHeight-kStatusBarAndNavigationBarHeight);
    self.bgSc.backgroundColor = kRGBColor(245, 245, 245);
    [self.view addSubview:self.bgSc];
    
    self.topLab = [BBControl createLabelWithFrame:CGRectMake(10, 15, kScreenWidth-20, 100) Font:16 Text:@"申请转运金"];
    self.topLab.backgroundColor = [UIColor clearColor];
    self.topLab.textAlignment = NSTextAlignmentCenter;
    [self.bgSc addSubview:self.topLab];
    self.topLab.textColor = kRGBColor(63, 63, 63);
    
    self.btnsView = [BBControl createViewWithFrame:CGRectMake(0, self.topLab.bottom+20, kScreenWidth, 200)];
    [self.bgSc addSubview:self.btnsView];
    
    
    NSString *str = @"活动时间\n\n2019年07月01日——31日\n\n活动适用平台\n\n所有老虎机平台\n\n活动内容\n\nEDF壹定发特色 自助转运金申请系统 再次升级，不仅申请更方便，而且奖励比例更高！\nEDF壹定发会员如果在老虎机平台中，因游戏不理想而产生输值，EDF壹定发将送您当日负盈利的 最低10%、最高15%作为转运金，每日最高 8888元，助您时来运转，翻本逆袭！\n每次申请前的有效输值不同，获得的转运金比例也不同，即每次申请转运金时输值越高，可获得的转运金会比提前领取更高哦！转运金=负盈利（当日存款-当日提款-当前余额）*返奖比例，具体比例如下：";
    NSArray *arr = @[@"活动时间",@"活动适用平台",@"活动内容"];
    NSArray *arr2 = @[@"自助转运金申请系统",@"最低10%、最高15%",@"8888元"];
    EDRichTextLabel * leb01 = [[EDRichTextLabel alloc]initWithFrame:CGRectMake(20, self.btnsView.bottom+20, kScreenWidth-40, 500)];
    leb01.backgroundColor = kRGBColor(245, 245, 245);
    [leb01 rich_TextCofigWith:str blodStrArry:arr colortextArry:arr2];
    [leb01 sizeToFit];
    [self.bgSc addSubview:leb01];
    
    UIView * numBgView = [BBControl createViewWithFrame:CGRectMake(10, leb01.bottom+20, kScreenWidth-20, 240)];
    KViewBorder(numBgView, kRGBColor(90, 90, 90), 1);
    [self.bgSc addSubview:numBgView];
    
    
    NSArray *dataArry = @[@[@"单次领取转运金时的输值",@"返奖比例",],@[@"≥200",@"10%",],@[@"≥2000",@"11%",],@[@"≥5000",@"12%",],@[@"≥10000",@"13%",],@[@"≥50000",@"15%",]];
    CGFloat  space = 0;
    CGFloat  btnH = 40;
    for (int i = 0 ; i < dataArry.count; i++) {
        NSInteger index = i % 1;
        NSInteger page = i / 1;
        NSArray * titles=dataArry[i];
        TwoBtnsView*mapBtn =[[NSBundle mainBundle]loadNibNamed:@"TwoBtnsView" owner:self options:nil].lastObject;
        mapBtn.frame = CGRectMake(index * (kScreenWidth-20 ), page  * (40 + space), kScreenWidth-20 , btnH);
        mapBtn.leftLab.text = titles.firstObject;
        mapBtn.rightLab.text = titles.lastObject;
        if (i==dataArry.count-1) {
            mapBtn.rightLab.textColor = EDColor_BaseBlue;
        }
        
        [numBgView addSubview:mapBtn];
    }
    
    
    NSString *str22 = @"当日只有同时满足以下2个条件才可申请转运金:\n(转运金计算不包含BBIN，捕鱼、真人、棋牌平台的输值)\n①负盈利（当日存款额-当日提款额-当前余额）≥195元；②所有账户累加有效余额≤5元。其中，累计存款仅计算基本账户的存款，即笔笔送、BBIN、沙巴和其他活动的存款金额不计入当日累计存款额。\n\n参加方式\n\n在【个人中心】--【自助服务区】——【申请转运金】按钮进行自助申请，待系统自动通过后即可在【个人中心】——【福利领取中心】——【红利】中领取。\n转运金必须在 当天23:59之前申请 ，申请通过后需在福利领取中心领取。转运金为系统自动派发，无法人工补派，请合理安排申请时间，把握转运时机。 \n\n活动规则\n\nEDF壹定发会定期与不定期举办各种优惠活动，在您参与前，您必须完全同意以下规则和履行以下义务：\n1、达到申请条件的玩家，每日至少可以领取一次转运金。级别越高，每日领取的次数越多：银冠会员为1次；金冠VIP会员为2次；王冠VIP会员为3次；皇冠VIP会员为4次；至尊VIP会员为5次。对于VIP会员：如当日第二次申请转运金，为上次领完转运金后的（存款-提款-余额）*对应返奖比例，以此类推；\n2、转运金每日最高可达 8888元。所有转运金将领取至“转运金”账户，10倍流水即可申请提款，可投注与老虎机平台（除BBIN）。转运金投注不计算返水；\n3、本优惠是特别为EDF壹定发在线娱乐玩家而设，如发现任何滥用优惠活动的个人或团体等尝试或进行恶意的欺诈行为，以利用红利为获得利润为目的，公司将对违规帐户进行冻结并索回红利及所有盈利；\n4、此活动必须遵守EDF壹定发一般规则与条款(请详细阅读)。EDF壹定发保留在任何时候对本活动的修改、停止及最终解释权。";
    NSArray *arr22 = @[@"参加方式",@"活动规则"];
    NSArray *arr222 = @[@"(转运金计算不包含BBIN，捕鱼、真人、棋牌平台的输值)",@"当天23:59之前申请",@"8888元",@"除BBIN",@"转运金投注不计算返水",];
    EDRichTextLabel * leb02 = [[EDRichTextLabel alloc]initWithFrame:CGRectMake(20, numBgView.bottom+20, kScreenWidth-40, 500)];
    leb02.backgroundColor = kRGBColor(245, 245, 245);
    [leb02 rich_TextCofigWith:str22 blodStrArry:arr22 colortextArry:arr222];
    [leb02 sizeToFit];
    [self.bgSc addSubview:leb02];
    self.bgSc.contentSize = CGSizeMake(kScreenWidth, leb02.bottom+50);
    
    
    
    
}

-(void)getLuckInfo{
    [self showLoadingAnimation];
    NSString  * balance = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Game_loadLuckyPromotion"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :balance parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
  
        STRONGSELFFor(weakSelf);
        //NSLog(@"User_getActivityAll---%@",responseObject);
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dataDicc = [dict jsonDict:@"data"];
            YYLog(@"Game_loadLuckyPromotion---%@",dict);
            //PTimageGameURL
            
          dispatch_async(dispatch_get_main_queue(), ^{
   [self creatBtnsView:[dataDicc jsonArray:@"bonus_list"]];
                NSString *HTMLString = [NSString stringWithFormat:@"<html><body><p>%@</p></body></html>", [dataDicc jsonString:@"tips_txt"] ];
                
                NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                                          NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)
                                          };
                NSData *data = [HTMLString dataUsingEncoding:NSUTF8StringEncoding];
                
                NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
                
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];   // 调整行间距
                paragraphStyle.lineSpacing = 5.0;
                paragraphStyle.alignment = NSTextAlignmentCenter;
                [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
                [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attributedString.length)];
                self.topLab.attributedText = attributedString;
                self.topLab.textAlignment =NSTextAlignmentCenter;
//                [self.bgSc.mj_header endRefreshing];
         });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
                // [self.bgSc.mj_header endRefreshing];
            });
        }
             [self stopLoadingAnimation];
    } failure:^(id responseObject, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopLoadingAnimation];
            [self.bgSc.mj_header endRefreshing];
            [WJUnit showMessage:@"请求失败"];
            // [self.bgSc.mj_header endRefreshing];
        });
 
        //[self getBalance];
        
    }];

}

-(void)creatBtnsView:(NSArray *)btnsArry{
    
    
    self.modelsArry = [NSMutableArray arrayWithArray:btnsArry];
    [self.btnsView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat  btnW = (kScreenWidth-120)/3;
    
    for (int i = 0 ; i < btnsArry.count; i++) {
        NSDictionary * dicc = [btnsArry objectAtIndex:i ];
        NSInteger index = i % 3;
        NSInteger page = i / 3;
        // 圆角按钮
        UIButton *mapBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        mapBtn.tag = i;//这句话不写等于废了
        mapBtn.frame = CGRectMake(index * (btnW + Width_Space) + Start_X, page  * (Button_Height + Height_Space)+Start_Y, btnW, Button_Height);
        [mapBtn setTitle:[NSString stringWithFormat:@"%@",[dicc jsonString:@"name"]] forState:0];
        [mapBtn setTitleColor:[UIColor whiteColor] forState:0];
        KViewRadius(mapBtn, 4);
        if ([[dicc jsonString:@"status"] isEqualToString:@"valid"]) {
            [mapBtn setBackgroundColor:kRGBColor(44, 143, 219) forState:0];
            mapBtn.enabled = YES;
        }else if ([[dicc jsonString:@"status"] isEqualToString:@"invalid"]){
            [mapBtn setBackgroundColor:kRGBColor(161, 161, 161) forState:0];
            mapBtn.enabled = NO;
        }else{
            //finish
            [mapBtn setBackgroundColor:kRGBColor(161, 161, 161) forState:0];
            mapBtn.enabled = NO;
        }
        if (i==btnsArry.count-1) {
            self.btnsView.height = mapBtn.bottom+15;
        }
        [mapBtn addTarget:self action:@selector(mapBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.btnsView addSubview:mapBtn];
        
    }
    
    
}
-(void)mapBtnClick:(UIButton*)sender{
    
    //Game_onGetDailyGameBonus
    [self showLoadingAnimation];
  //  NSDictionary * dicc = self.modelsArry[sender.tag];
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Game_onGetluckyBonus"];

    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            YYLog(@"loadDailySignPromotion----%@",dict001);
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"success" andTitleStr:[dict001 jsonString:@"data"] andlightStr:@""];
                [toast showLXAlertView];
                [sender setBackgroundColor:kRGBColor(161, 161, 161) forState:0];
                sender.enabled = NO;
                [self getLuckInfo];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        NSLog(@"error----%@",error);
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
    
    
    
    
}

@end
